import { getYapiInterface } from "../../../api/yapi";
import { registerMessage } from "./register";
import * as vscode from 'vscode';
import { compile } from 'json-schema-to-typescript';
import * as Mock from 'mockjs';
import * as jsf from 'json-schema-faker';

jsf.JSONSchemaFaker.extend('mock', () => Mock.Random);

/**
 * 登录 yapi
 */
registerMessage('toLogin', () => {
  console.log('toLogin');

  const loginUrl = 'https://example.com/login'; // 替换为你的登录 URL
  // 打开浏览器

  vscode.env.openExternal(vscode.Uri.parse(loginUrl));
});

/**
 * 获取 yapi 项目
 */
registerMessage('getYapiProject', async (payload:any) => {
  const config = vscode.workspace.getConfiguration('zd-vscode-tools');
});

/**
 * 获取 yapi 接口
 */
registerMessage('getYapiInterface', async (payload:any) => {
  console.log('getYapiInterface', payload);
  const { id } = payload;
  const res = await getYapiInterface({ id });

  return res;
});


/**
 * 首字母大写
 * @param str
 * @returns
 */
function capitalizeFirstLetter(str:string) {
  if (!str) return str; // 处理空字符串
  return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * 编译 json 为 typescript 接口
 */
registerMessage('compileJSON', async (payload:any) => {
  console.log('compileJSON', payload);
  const { req_body_other, res_body, path } = payload;

  const req = JSON.parse(req_body_other);
  const res = JSON.parse(res_body);

  if (!path) return { reqSchema: '', resSchema: '' };

  const pathArr = path.split('/');
  const pathArrReverse = pathArr.reverse();
  const fnName = [ pathArrReverse[1], capitalizeFirstLetter(pathArrReverse?.[0]) ].join('');
  const reqInterfaceName = capitalizeFirstLetter(fnName) + 'Req';
  const resInterfaceName = capitalizeFirstLetter(fnName) + 'Resp';

  const options = {
    bannerComment: "",
    additionalProperties: false,
    style: {
      bracketSpacing: true,
    },
  };

  delete req?.properties?.requestId;
  delete req?.properties?.page;

  const reqSchema = await compile(req, reqInterfaceName, options);
  const resSchema = await compile(res.properties?.data ?? {}, resInterfaceName, options);
  const resSchemaMock = JSON.stringify(jsf.JSONSchemaFaker.generate(res.properties?.data), null, 4);

  console.log('resSchemaMock', resSchemaMock);

  return {
    reqSchema,
    resSchema,
    resSchemaMock,
  };
});


registerMessage('setCookie', (payload:any) => {
  const { cookie } = payload;

  console.log('setCookie', cookie);
  vscode.workspace.getConfiguration('zd-vscode-tools').update('yapiCookie', cookie, vscode.ConfigurationTarget.Global);
  return true;
});

registerMessage('getCookie', () => {
  return vscode.workspace.getConfiguration('zd-vscode-tools').get('yapiCookie');
});